import { useState, useEffect } from 'react';
import { Card, Button, Modal, message, Form, Popconfirm } from 'antd';
import TimerList from '@/components/timer/TimerList';
import TimerForm from '@/components/timer/TimerForm';
import { getTimers, createTimer, updateTimer, deleteTimer, toggleTimerStatus } from '@/services/timer';
import { getDevices } from '@/services/device';
import { TimerDTO, TimerVO } from '@/types/timer';
import { Device } from '@/types/device';

const TimerPage = () => {
  const [timers, setTimers] = useState<TimerVO[]>([]);
  const [devices, setDevices] = useState<Device[]>([]);
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [editingTimer, setEditingTimer] = useState<TimerVO | null>(null);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      setLoading(true);
      const [timersData, devicesData] = await Promise.all([
        getTimers(),
        getDevices()
      ]);
      setTimers(timersData);
      setDevices(devicesData);
    } catch (error: any) {
      message.error(error.message || '加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = async (values: TimerDTO) => {
    try {
      await createTimer(values);
      message.success('创建成功');
      setVisible(false);
      form.resetFields();
      loadData();
    } catch (error: any) {
      message.error(error.message || '创建失败');
    }
  };

  const handleUpdate = async (values: TimerDTO) => {
    if (!editingTimer) return;
    try {
      await updateTimer(editingTimer.id, values);
      message.success('更新成功');
      setVisible(false);
      setEditingTimer(null);
      form.resetFields();
      loadData();
    } catch (error: any) {
      message.error(error.message || '更新失败');
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteTimer(id);
      message.success('删除成功');
      loadData();
    } catch (error: any) {
      message.error(error.message || '删除失败');
    }
  };

  const handleStatusChange = async (id: number) => {
    try {
      await toggleTimerStatus(id);
      message.success('状态更新成功');
      loadData();
    } catch (error: any) {
      message.error(error.message || '状态更新失败');
    }
  };

  const showModal = (timer?: TimerVO) => {
    setEditingTimer(timer || null);
    form.resetFields();
    if (timer) {
      form.setFieldsValue({
        name: timer.name,
        deviceId: timer.deviceId,
        intervalMinutes: timer.intervalMinutes,
        targetStatus: timer.targetStatus,
        status: timer.status
      });
    }
    setVisible(true);
  };

  return (
    <Card
      title="定时任务管理"
      extra={
        <Button type="primary" onClick={() => showModal()}>
          新建定时任务
        </Button>
      }
      loading={loading}
    >
      <TimerList
        timers={timers}
        onEdit={showModal}
        onDelete={(id) => {
          Modal.confirm({
            title: '确认删除',
            content: '确定要删除这个定时任务吗？',
            onOk: () => handleDelete(id)
          });
        }}
        onStatusChange={handleStatusChange}
      />

      <Modal
        title={editingTimer ? '编辑定时任务' : '新建定时任务'}
        open={visible}
        onOk={() => form.submit()}
        onCancel={() => {
          setVisible(false);
          setEditingTimer(null);
          form.resetFields();
        }}
        maskClosable={false}
      >
        <TimerForm
          form={form}
          devices={devices}
          initialValues={editingTimer || undefined}
          onFinish={editingTimer ? handleUpdate : handleCreate}
        />
      </Modal>
    </Card>
  );
};

export default TimerPage; 